package jmine.tec.subscription.impl;

import jmine.tec.subscription.Publication;
import jmine.tec.subscription.Publisher;
import jmine.tec.subscription.SubscriptionSettings;
import jmine.tec.subscription.replicator.PartialPublicationWrapper;
import jmine.tec.subscription.replicator.PublicationWrapper;

import org.springframework.context.ApplicationEventPublisher;

/**
 * Usa a engine do spring para rotear eventos ate o(s) subscriptionManager
 * 
 * @author takeshi
 */
public final class ApplicationEventRouter implements EventRouter {

    private final ApplicationEventPublisher applicationEventPublisher;

    /**
     * C'tor
     * 
     * @param applicationEventPublisher o {@link ApplicationEventPublisher} que deve enviar os eventos
     */
    public ApplicationEventRouter(ApplicationEventPublisher applicationEventPublisher) {
        super();
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * {@inheritDoc}
     */
    public <P extends Publication> void broadcast(SubscriptionSettings settings, Publisher<P> publisherId, P publication) {
        this.applicationEventPublisher.publishEvent(new PublicationWrapper(settings, publisherId.identification(), publication));
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public <P extends Publication> void broadcastPartialPublication(SubscriptionSettings settings, Publisher<P> publisher,
            PartialPublication<P> partial) {
        this.applicationEventPublisher.publishEvent(new PartialPublicationWrapper(settings, publisher.identification(),
                (PartialPublication<Publication>) partial));
    }

}
